package lnu.project.cart;

import java.util.ArrayList;
import java.util.List;

import lnu.project.cart.entity.Basket;
import lnu.project.cart.entity.Product;
import lnu.project.cart.entity.TypeOfProduct;
import lnu.project.cart.provider.BasketProvider;
import lnu.project.cart.provider.IBasketProvider;
import lnu.project.cart.provider.IProductProvider;
import lnu.project.cart.provider.ProductProvider;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

public class BasketActivity extends ListActivity {
	/** Providers **/
	private IProductProvider productProvider;
	private IBasketProvider basketProvider;

	/** Called when the activity is first created. */

	private Basket myBasket;
	private List<Product> products = new ArrayList<Product>();

	public static final int ADDPRODUCT = 0;
	private ListActivity this_activity2;
	public static final int EDITPRODUCT = 0;
	public static final int DELETEPRODUCT = 1;
	public static final int SEARCHPRODUCT = 2;

	private ListAdapter adapter;

	public static String PRODUCTNAME, PRODUCTPRICE, PRODUCTWEIGHT,
			PRODUCTQUANTITY;
	public static int POSITION;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main);
		this_activity2 = this;
		InitProviders();

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			String sid = bundle.getString("basketId");
			myBasket = basketProvider.Get(Long.parseLong(sid));
			System.out.println("Basket's Id: " + myBasket.getId() + ", Name: "
					+ myBasket.getName());
			myBasket = this.productProvider.LoadProduct(myBasket);
			System.out.println("Before load product!");
		}

		/* Adapter */
		adapter = new ProductAdapter(this, R.layout.basket_xml);
		setListAdapter(adapter);
		/* Attach context menu on list */
		registerForContextMenu(getListView());

		RefreshList();
	}

	private void InitProviders() {
		this.productProvider = new ProductProvider();
		this.productProvider.SetActivity(this_activity2);

		this.basketProvider = new BasketProvider();
		this.basketProvider.SetActivity(this_activity2);
	}

	private void RefreshList() {
		products.clear();
		myBasket = this.productProvider.LoadProduct(myBasket);
		for (Product item : myBasket.getProducts()) {
			products.add(item);
		}
		((BaseAdapter) adapter).notifyDataSetChanged();
	}

	class ProductAdapter extends ArrayAdapter<Product> {

		public ProductAdapter(Context context, int textViewResourceId) {
			super(context, textViewResourceId, products);
		}

		@Override
		// Called when updating the ListView
		public View getView(int position, View convertView, ViewGroup parent) {
			View row;
			if (convertView == null) { // Create new row view object
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.basket_xml, parent, false);
			} else
				// reuse old row view to save time/battery
				row = convertView;

			Product cProduct = products.get(position);

			/* Add new data to row object */
			TextView ProducT = (TextView) row.findViewById(R.id.Product_name);
			String name = cProduct.getName().toString();
			ProducT.setText(name);

			ImageView icon = (ImageView) row.findViewById(R.id.iconProductType);
			TextView quantitytext = (TextView) row.findViewById(R.id.unit);
			String perUnitText = "";
			if (cProduct.getTypeOfProduct() == 0) {
				icon.setImageResource(R.drawable.counticon);
				quantitytext.setText(String.valueOf(cProduct.getQuantity()));
				perUnitText = String.format("Price per item: %.2f",
						cProduct.getPrice());
			} else if (cProduct.getTypeOfProduct() == 1) {
				icon.setImageResource(R.drawable.weighticon);
				quantitytext.setText(String.valueOf(cProduct.getWeight()));
				perUnitText = String.format("Price per weight: %.2f",
						cProduct.getPrice());
			}

			// Set total price
			TextView pricetext = (TextView) row.findViewById(R.id.price);
			pricetext.setText(String.format("Total: %.2f",
					cProduct.GetTotalPrice()));

			TextView weighttext = (TextView) row.findViewById(R.id.weight);
			weighttext.setText(perUnitText);

			return row;
		}
	}

	/*
	 * Adding one option menu
	 */

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		MenuItem m1 = menu.add(0, ADDPRODUCT, 0, "New Product"); // Create menu
																	// 1
		m1.setIcon(android.R.drawable.ic_input_add); // Attach icon

		return result;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ADDPRODUCT:
			Intent intent = new Intent(this_activity2, AddNewProduct.class);
			this_activity2.startActivityForResult(intent, 0);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent result) {
		if (resultCode == RESULT_OK) {
			int flag = Integer.parseInt(result.getStringExtra("flag"));
			System.out.println("Flag:" + flag);

			Long id = result.getLongExtra("id", 0);
			String name = result.getStringExtra("name");
			Integer type = result.getIntExtra("productType", 0);
			String barcode = result.getStringExtra("barcode");
			Integer quantity = result.getIntExtra("quantity", 0);
			Float weight = result.getFloatExtra("weight", 0);
			Float price = result.getFloatExtra("price", 0);

			if (flag == 0) {
				System.out.println("New Product");

				Product newProduct = new Product(type, name, barcode, quantity,
						weight, price);

				productProvider.Create(myBasket.getId(), newProduct);
			} else if (flag == 1) {
				System.out.println("Edit Product");

				Product editProduct = productProvider.Get(id);
				editProduct.setName(name);
				editProduct.setTypeOfProduct(type);
				editProduct.setBarcode(barcode);
				editProduct.setQuantity(quantity);
				editProduct.setWeight(weight);
				editProduct.setPrice(price);

				productProvider.Update(editProduct);
			}
		}
		RefreshList();
	}

	/*
	 * Adding two context menus
	 */

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("Context Menu");
		menu.add(0, SEARCHPRODUCT, 0, "Search in the Internet");
		menu.add(0, EDITPRODUCT, 0, "Edit Product");
		menu.add(0, DELETEPRODUCT, 0, "Delete Product");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int pos = info.position;

		switch (item.getItemId()) {
		case EDITPRODUCT:
			POSITION = pos;
			Intent intent = new Intent(this_activity2, EditProduct.class);
			intent.putExtra("productId", products.get(pos).getId());
			this_activity2.startActivityForResult(intent, 0);
			break;
		case DELETEPRODUCT:
			Product deleteProduct = products.get(pos);
			productProvider.Delete(deleteProduct.getId());
			System.out.println("Product deleted");
			break;
		case SEARCHPRODUCT:
			Product searchProduct = products.get(pos);
			
			String webPage = "http://google.com/search?q=";
			webPage += searchProduct.getName();
			if (searchProduct.getBarcode() != null
					&& searchProduct.getBarcode() !=""){
				webPage += " " + searchProduct.getBarcode(); 
			}
			Intent webSearch = new Intent(Intent.ACTION_VIEW);
			webSearch.setData(Uri.parse(webPage));
			this_activity2.startActivity(webSearch);
			System.out.println("Product deleted");
			break;
		default:
			return super.onContextItemSelected(item);
		}
		RefreshList();
		return true;
	}
}
